package cn.webview;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;

import java.util.Set;

public class MainActivity extends AppCompatActivity {
    private WebView mWebView;
    private final String TAG = "MainActivity";
    private String name = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initWebView();
        initWebSetting();
        myWebViewClient();
        myWebChromeClient();
        btnCallJS();
    }

    private void myWebChromeClient() {
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                if (!message.equals("Android调用js")) {
                    Log.e(TAG, "message = " + message);
                    Uri uri = Uri.parse(message);
                    if (uri.getScheme().equals("js")) {
                        String id = uri.getQueryParameter("id");
                        Intent intent = new Intent(MainActivity.this, ActivityB.class);
                        intent.putExtra("id", id);
                        startActivity(intent);
                    }
                    result.confirm();
                }
                return super.onJsConfirm(view, url, message, result);
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                return super.onJsConfirm(view, url, message, result);
            }

            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, final JsPromptResult result) {
                Log.e(TAG, "message = " + message);
                Uri uri = Uri.parse(message);
                if (uri.getScheme().equals("js")) {
                    if (uri.getAuthority().equals("getName")) {
                        final EditText editText = new EditText(MainActivity.this);
                        AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this)
                                .setTitle("请输入姓名")
                                .setView(editText)
                                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        name = editText.getText().toString();
                                        result.confirm(name);
                                        dialog.cancel();
                                    }
                                }).create();
                        alertDialog.show();
                    }
                    return true;
                }
                return super.onJsPrompt(view, url, message, defaultValue, result);
            }
        });
    }

    private void btnCallJS() {
        findViewById(R.id.btn_JS).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //第一种Android调用JS方法
//                mWebView.loadUrl("javascript:callJS()");
                //第二种调用方法，Android4.4版本以上才能用，要判断版本
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    mWebView.evaluateJavascript("javascript:callJS()", new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(String value) {
                            //此处为JS返回的结果

                        }
                    });
                }
            }
        });
    }

    private void myWebViewClient() {
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                Log.e(TAG, "页面开始加载" + url);
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                Log.e(TAG, "页面加载完成" + url);
                super.onPageFinished(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.e(TAG, "url=" + url);
                Uri uri = Uri.parse(url);
                if (uri.getScheme().equals("js")) {
                    if (uri.getAuthority().equals("webview")) {
                        Set<String> paramSet = uri.getQueryParameterNames();
                        for (String param : paramSet) {
                            String value = uri.getQueryParameter(param);
                            Log.e(TAG, "param = " + param + " value = " + value);
                        }
                    }
                    return true;
                }
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }
        });
    }

    @SuppressLint("JavascriptInterface")
    private void initWebSetting() {
        WebSettings webSettings = mWebView.getSettings();
        //设置与js交互的权限
        webSettings.setJavaScriptEnabled(true);
        //设置允许js弹窗
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        //JSToAndroid类对象映射到js的test对象
        mWebView.addJavascriptInterface(new JSToAndroid(MainActivity.this), "test");
    }

    private void initWebView() {
        mWebView = findViewById(R.id.m_webView);

        /*
         * 第一种，直接加载url
         * */
        //mWebView.loadUrl("https://www.baidu.com");

        /*
         * 第二种，加载asset文件夹下的html
         * */
        mWebView.loadUrl("file:///android_asset/test.html");

        /*
         * 第三种，使用webview显示html代码
         * */
//        String htmlContent = "<!DOCTYPE html>\n" +
//                "<html lang=\"en\">\n" +
//                "<meta charset=\"utf-8\">\n" +
//                "<body>\n" +
//                "\t<h1>欢迎</h1>\n" +
//                "\t<img src=\"file:///android_asset/1.png\" >\n" +
//                "</body>\n" +
//                "</html>";
//        mWebView.loadDataWithBaseURL(null,htmlContent,"text/html","utf-8",null);
    }


    //设置返回键返回上一个网页
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mWebView.canGoBack() && keyCode == KeyEvent.KEYCODE_BACK) {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
